<template>
	<view class="chat-container">
		<!-- 自定义导航栏 -->
		<view class="custom-nav-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="nav-content">
				<view class="nav-left">
					<text class="back-icon" @click="goBack">〈</text>
				</view>
				<view class="nav-title">
					<text class="title-text">{{shopName || '杭州酒小二x123'}}</text>
				</view>
				<view class="nav-right">
					<view class="nav-actions">
						<text class="action-icon">...</text>
						<text class="action-icon">-</text>
						<text class="action-icon">○</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 聊天内容区域 -->
		<view class="chat-content">
			<view class="message-list">
				<view 
					class="message-item" 
					v-for="(message, index) in messages" 
					:key="index"
					:class="message.type === 'user' ? 'user-message-item' : 'service-message-item'"
				>
					<!-- 用户消息 -->
					<view v-if="message.type === 'user'" class="message-header user-message-header">
						<view class="message-info">
							<text class="user-name">{{message.sender || '我'}}</text>
							<text class="message-time">{{formatTime(message.number)}}</text>
						</view>
						<view class="user-avatar">
							<image src="/static/img/a.png" mode="aspectFill" class="avatar-img"></image>
						</view>
					</view>
					<view v-if="message.type === 'user'" class="message-bubble user-message">
						<text class="bubble-text">{{message.content}}</text>
					</view>
					
					<!-- 客服消息 -->
					<view v-if="message.type === 'service'" class="message-header service-message-header">
						<view class="service-avatar">
							<image src="/static/img/a.png" mode="aspectFill" class="avatar-img"></image>
						</view>
						<view class="message-info">
							<text class="service-name">{{message.sender || '客服'}}</text>
							<text class="message-time">{{formatTime(message.number)}}</text>
						</view>
					</view>
					<view v-if="message.type === 'service'" class="message-bubble service-message">
						<text class="bubble-text">{{message.content}}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部输入区域 -->
		<view class="input-area">
			<view class="input-container">
				<input 
					class="message-input" 
					placeholder="用一句简短的话描述您的问题" 
					v-model="inputMessage"
					@confirm="sendMessage"
				/>
				<button class="send-btn" @click="sendMessage">发送</button>
			</view>
		</view>
	</view>
</template>

<script>
	import webSocketManager from '@/utils/websocket.js'
	import { get, post } from '@/config/request.js'

	export default {
		data() {
			return {
				statusBarHeight: 0, // 状态栏高度
				inputMessage: '', // 输入框内容
				shopName: '', // 店铺名称
				shopId: '', // 店铺ID
				username: '', // 当前登录用户名
				websocket: null, // WebSocket连接
				isConnected: false, // 连接状态
				messages: [
					{
						number: '5156',
						content: '5156',
						type: 'user' // 消息类型：user-用户消息，service-客服消息
					},
					{
						number: '2565466',
						content: '2565466',
						type: 'service'
					}
				]
			}
		},
		onLoad(options) {
			// 获取状态栏高度
			this.getStatusBarHeight()
			// 接收页面参数
			if (options.shopName) {
				this.shopName = decodeURIComponent(options.shopName)
			}
			if (options.shopId) {
				this.shopId = options.shopId
			}
			// 获取当前登录用户名
			this.getCurrentUser()
				// 获取聊天记录
				this.getChatHistory()
		},
		onShow() {
			// 页面显示时建立WebSocket连接
			this.connectWebSocket()
		},
		onHide() {
			// 页面隐藏时移除消息回调
			this.removeMessageCallback()
		},
		onUnload() {
			// 页面卸载时移除消息回调
			this.removeMessageCallback()
		},
		methods: {
			// 获取状态栏高度
			getStatusBarHeight() {
				const systemInfo = uni.getSystemInfoSync()
				this.statusBarHeight = systemInfo.statusBarHeight
			},
			
			// 获取当前登录用户
			getCurrentUser() {
				// 从本地存储获取用户信息
				const userInfo = uni.getStorageSync('userInfo')
				if (userInfo && userInfo.memberName) {
					this.username = userInfo.memberName
				} else {
					// 如果没有登录，使用默认用户名
					this.username = 'guest_' + Date.now()
				}
			},
			
			// 建立WebSocket连接
			connectWebSocket() {
				if (!this.username) {
					console.log('用户名未设置，无法建立连接')
					return
				}

				// 使用WebSocket管理工具建立连接
				webSocketManager.connect(this.username, this.handleWebSocketMessage)
				
				// 更新连接状态
				this.isConnected = webSocketManager.getConnectionStatus()
				
				if (this.isConnected) {
					// 添加连接成功消息
					this.addMessage('系统', '连接成功，客服为您服务', 'service')
				}
			},
			
			// 处理WebSocket消息
			handleWebSocketMessage(data) {
				console.log('收到WebSocket消息:', data)
				// 兼容三种形态：
				// 1) 纯文本/数字 → wrapper 可能传 { msg: '...' } 或直接原始值
				// 2) { msg: '...' }
				// 3) { from: 'xxx', content: '...' } 或 { text/message }
				let from = '客服'
				let content = ''
				if (data && typeof data === 'object') {
					from = data.from || '客服'
					content = data.content ?? data.msg ?? data.text ?? data.message ?? ''
				} else if (data !== undefined && data !== null) {
					content = String(data)
				}
				if (content !== '') {
					this.addMessage(from, content, 'service')
				}
			},
			
			// 移除消息回调
			removeMessageCallback() {
				webSocketManager.removeMessageCallback(this.handleWebSocketMessage)
			},
			
			// 调用onopen接口
			callOnOpen() {
				// 这里可以发送一个初始化消息给服务器
				console.log('调用onopen接口，用户名:', this.username)
			},
			
			// 返回上一页
			goBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			
			// 获取聊天记录
			async getChatHistory() {
				try {
					const me = this.username
					const peer = 'kefu'
					const before = Date.now()
					const pageSize = 50
					
					// 使用正确的请求方法
					const res = await get('/Chat/chat/history', { me, peer, before, pageSize })
					
					if (res && Array.isArray(res.data)) {
						this.messages = res.data.map(it => ({
							number: new Date(it.createdAt).getTime().toString(),
							content: it.content,
							type: it.fromUser === me ? 'user' : 'service',
							sender: it.fromUser === me ? '我' : '客服'
						}))
						this.$nextTick(() => this.scrollToBottom())
					}
					
					// 标记已读
					await post('/Chat/chat/read', { me, peer })
				} catch (e) {
					console.log('加载历史失败', e)
					// 如果历史记录加载失败，至少显示一些默认消息
					this.messages = [
						{
							number: Date.now().toString(),
							content: '欢迎使用客服系统',
							type: 'service',
							sender: '客服'
						}
					]
				}
			},
			
			// 添加消息到列表
			addMessage(sender, content, type) {
				this.messages.push({
					number: Date.now().toString(),
					content: content,
					type: type, // user-用户消息，service-客服消息
					sender: sender
				})
				// 滚动到底部
				this.$nextTick(() => {
					this.scrollToBottom()
				})
			},
			
			// 滚动到底部
			scrollToBottom() {
				const query = uni.createSelectorQuery().in(this)
				query.select('.message-list').boundingClientRect()
				query.selectViewport().scrollOffset()
				query.exec((res) => {
					if (res[0]) {
						uni.pageScrollTo({
							scrollTop: res[0].height,
							duration: 300
						})
					}
				})
			},
			
			// 发送消息
			async sendMessage() {
				if (!this.inputMessage.trim()) {
					uni.showToast({
						title: '请输入消息内容',
						icon: 'none'
					})
					return
				}
				
				const message = this.inputMessage.trim()
				
				// 添加用户消息到列表
				this.addMessage(this.username, message, 'user')
				
				// 使用WebSocket管理工具发送消息
				try {
					await webSocketManager.sendMessage(message)
					console.log('消息发送成功:', message)
				} catch (error) {
					console.error('消息发送失败:', error)
					uni.showToast({
						title: '发送失败，请检查连接',
						icon: 'none'
					})
				}
				
				// 清空输入框
				this.inputMessage = ''
			},
			
			// 调用onmessage接口
			callOnMessage(message) {
				console.log('调用onmessage接口，消息:', message, '用户名:', this.username)
				// 这里可以发送消息到后端ChatService的onMessage方法
				// 后端会处理消息并返回响应
			},
			
			// 格式化时间
			formatTime(timestamp) {
				const date = new Date(parseInt(timestamp))
				const now = new Date()
				const diff = now - date
				
				// 如果是今天
				if (date.toDateString() === now.toDateString()) {
					return date.toLocaleTimeString('zh-CN', { 
						hour: '2-digit', 
						minute: '2-digit' 
					})
				}
				// 如果是昨天
				const yesterday = new Date(now)
				yesterday.setDate(yesterday.getDate() - 1)
				if (date.toDateString() === yesterday.toDateString()) {
					return '昨天 ' + date.toLocaleTimeString('zh-CN', { 
						hour: '2-digit', 
						minute: '2-digit' 
					})
				}
				// 其他日期
				return date.toLocaleDateString('zh-CN', { 
					month: '2-digit', 
					day: '2-digit',
					hour: '2-digit', 
					minute: '2-digit' 
				})
			}
		}
	}
</script>

<style scoped>
	.chat-container {
		background-color: #f8f9fa;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
		padding-bottom: env(safe-area-inset-bottom);
	}

	/* 自定义导航栏样式 */
	.custom-nav-bar {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		z-index: 999;
		border-bottom: 1rpx solid #e8e8e8;
	}

	.nav-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 30rpx;
		height: 88rpx;
	}

	.nav-left {
		display: flex;
		align-items: center;
	}

	.back-icon {
		font-size: 36rpx;
		color: #333;
		padding: 8rpx;
		border-radius: 50%;
		transition: background-color 0.2s ease;
	}

	.back-icon:active {
		background-color: #f0f0f0;
	}

	.nav-title {
		flex: 1;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.title-text {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.nav-right {
		display: flex;
		align-items: center;
	}

	.nav-actions {
		display: flex;
		align-items: center;
	}

	.action-icon {
		font-size: 24rpx;
		color: #666;
		margin-left: 15rpx;
	}

	/* 聊天内容区域 */
	.chat-content {
		flex: 1;
		margin-top: 108rpx;
		margin-bottom: 120rpx;
		padding: 20rpx;
	}

	.message-list {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.message-item {
		display: flex;
		flex-direction: column;
		margin-bottom: 30rpx;
	}

	/* 用户消息样式 */
	.user-message-item {
		align-items: flex-end;
	}

	/* 客服消息样式 */
	.service-message-item {
		align-items: flex-start;
	}

	.message-header {
		display: flex;
		align-items: center;
		margin-bottom: 12rpx;
	}

	.message-info {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
	}

	.user-name, .service-name {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
		margin-bottom: 4rpx;
	}

	.message-time {
		font-size: 24rpx;
		color: #999;
	}

	.user-avatar, .service-avatar {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		overflow: hidden;
		background-color: #f0f0f0;
		flex-shrink: 0;
	}

	.avatar-img {
		width: 100%;
		height: 100%;
	}

	.message-bubble {
		padding: 16rpx 20rpx;
		border-radius: 18rpx;
		max-width: 70%;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
		position: relative;
	}

	/* 用户消息气泡 */
	.user-message {
		background-color: #ff6b6b;
		align-self: flex-end;
		margin-left: auto;
		box-shadow: 0 2rpx 8rpx rgba(255, 107, 107, 0.2);
	}

	.user-message .bubble-text {
		color: #fff;
	}

	/* 客服消息气泡 */
	.service-message {
		background-color: #fff;
		align-self: flex-start;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
	}

	.service-message .bubble-text {
		color: #333;
	}

	.bubble-text {
		font-size: 28rpx;
		line-height: 1.4;
		font-weight: 400;
	}

	/* 用户消息头部 */
	.user-message-header {
		flex-direction: row;
		justify-content: flex-end;
	}

	.user-message-header .message-info {
		margin-right: 15rpx;
		margin-left: 0;
		align-items: flex-end;
	}

	/* 客服消息头部 */
	.service-message-header {
		flex-direction: row;
		justify-content: flex-start;
	}

	.service-message-header .message-info {
		margin-left: 15rpx;
		margin-right: 0;
		align-items: flex-start;
	}

	/* 底部输入区域 */
	.input-area {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		border-top: 1rpx solid #e8e8e8;
		padding: 20rpx 30rpx;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	}

	.input-container {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.message-input {
		flex: 1;
		background-color: #f8f9fa;
		border-radius: 25rpx;
		padding: 15rpx 20rpx;
		font-size: 28rpx;
		color: #333;
		border: 1rpx solid #e8e8e8;
		transition: all 0.2s ease;
	}

	.message-input:focus {
		background-color: #fff;
		border-color: #ff6b6b;
		box-shadow: 0 0 0 2rpx rgba(255, 107, 107, 0.1);
	}

	.send-btn {
		background-color: #ff6b6b;
		color: #fff;
		border: none;
		border-radius: 25rpx;
		padding: 15rpx 30rpx;
		font-size: 28rpx;
		font-weight: 500;
		transition: all 0.2s ease;
		box-shadow: 0 2rpx 8rpx rgba(255, 107, 107, 0.2);
	}

	.send-btn:active {
		transform: scale(0.95);
		box-shadow: 0 1rpx 4rpx rgba(255, 107, 107, 0.3);
	}

	/* 响应式适配 */
	@media screen and (max-width: 750rpx) {
		.chat-content {
			padding: 15rpx;
		}
		
		.message-bubble {
			max-width: 80%;
		}
		
		.bubble-text {
			font-size: 26rpx;
		}
		
		.message-input {
			font-size: 26rpx;
		}
		
		.send-btn {
			font-size: 26rpx;
			padding: 12rpx 25rpx;
		}
	}

	@media screen and (max-width: 600rpx) {
		.chat-content {
			padding: 10rpx;
		}
		
		.message-bubble {
			max-width: 85%;
		}
		
		.bubble-text {
			font-size: 24rpx;
		}
		
		.message-input {
			font-size: 24rpx;
		}
		
		.send-btn {
			font-size: 24rpx;
			padding: 10rpx 20rpx;
		}
		
		.input-area {
			padding: 15rpx 20rpx;
		}
	}
</style>
